import logging

from django.core.cache import cache
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from home.models import NavCategory, CourseCategory, Banner
from home.ser import NavCategorySerializer, CourseCategorySerializer, BannerSerializer

logger = logging.getLogger("django")


# Create your views here.
class NavCategoryAPIView(APIView):

    def get(self, request):
        try:
            nav_category = NavCategory.objects.filter(is_deleted=False, is_show=True)
            ser = NavCategorySerializer(nav_category, many=True)

            return Response({
                "code": 1,
                "msg": "获取成功",
                "data": ser.data
            })
        except Exception as e:
            return Response({
                "code": 0,
                "msg": f"获取失败: {e}",
            })


class CourseCategoryAPIView(APIView):

    def get(self, request):
        queryset = CourseCategory.objects.filter(is_deleted=False, is_show=True, level=1)
        ser = CourseCategorySerializer(queryset, many=True)

        return Response({
            "code": 1,
            "msg": "获取成功",
            "data": ser.data
        })


class BannerAPIView(APIView):

    def get(self, request):
        try:
            cache_key = "code_env_spaces:home:banner"
            banner_redis = cache.get(cache_key)

            if banner_redis:
                logger.info(f"从redis获取轮播图数据成功,共{len(banner_redis)}条")
                return Response({
                    "code": 1,
                    "msg": "获取成功",
                    "data": banner_redis
                })

            banner = Banner.objects.filter(is_deleted=False, is_show=True)
            ser = BannerSerializer(banner, many=True)
            logger.info(f"从mysql获取轮播图成功,共{len(ser.data)}条")

            cache.set(cache_key, ser.data, timeout=60 * 60 * 240)

            return Response({
                "code": 1,
                "msg": "获取成功",
                "data": ser.data
            })
        except Exception as e:
            return Response({
                "code": 0,
                "msg": f"获取失败: {str(e)}",
            })
